<?php

class RaovatUserInfoController extends Controller {
    public function actionIndex() {
        Yii::app()->language = 'vi';
        if (!isset($_GET['user_id'])) throw new CHttpException(999, 'Invalid request');
        $id = $_GET['user_id'];
        $user = UserRaoVatInfo::model()->findByAttributes(array('user_id' => $id));
        $user_back = UserBack::model()->findByPk($user->user_id);
        if ($user == null) throw new CHttpException(999, 'Invalid request');

        $products = Product::model()->getForGridByUser($id);
        $buyWay = BuyWay::model()->findByAttributes(array('user_id' => $id));

        Yii::app()->language = 'vi';
        $criteria = new CDbCriteria();
        $criteria->select = '*';
        $criteria->condition = 'owner_id = :id';
        $criteria->params = array(':id' => $id);
        $criteria->order = 'guest_book_id DESC';

        $guestBooks = new CActiveDataProvider('GuestBook', array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => 10)
        ));

        $total = GuestBook::model()->count($criteria);
        if (isset ($_POST['buyWay'])) {
            if ($buyWay == null) {
                $buyWay = new BuyWay();
                $buyWay->user_id = Yii::app()->user->id;
                $buyWay->user_name = $user->user_name;
                $buyWay->detail = $_POST['buyWay'];
            } else {
                $buyWay->detail = $_POST['buyWay'];
            }
            if ($buyWay->save()) {
                $this->redirect(TreTodayUrl::getUserUrl($user_back->user_id, $user_back->user_name));
            }

        }

        if (isset($_POST['UserRaoVatInfo'])) {
            $user->phone = $_POST['UserRaoVatInfo']['phone'];
            $user->ym = $_POST['UserRaoVatInfo']['ym'];
            $user->address = $_POST['UserRaoVatInfo']['address'];
            $file = CUploadedFile::getInstance($user, 'image');

            if ($file != null) {
                $imageVariables = getimagesize($file->tempName);
                $file = EUploadedImage::getInstance($user, 'image');
                $arr_size = TreTodayCommon::getResizeImage($imageVariables[0], $imageVariables[1]);
                $file->maxWidth = $arr_size['width'];
                $file->maxHeight = $arr_size['height'];
                $rnd = rand(0, 999999);
                $fileName = "{$rnd}.jpg";
                $base = TreTodayCommon::createFolder('avata');
                $base = $base . '/' . $fileName;
                if ($file->saveAs($base)) {
                    $user_back->avata_url = TreTodayCommon::generateImagePath('avata', $fileName);
                    $user->avata_url = TreTodayCommon::generateImagePath('avata', $fileName);

                    $user_back->website = $_POST['UserRaoVatInfo']['website'];
                    $user_back->save();
                    if ($user->save()) {
                        $this->redirect(TreTodayUrl::getUserUrl($user_back->user_id, $user_back->user_name));
                    }
                }
            } else {
                $user_back->website = $_POST['UserRaoVatInfo']['website'];
                $user_back->save();
                if ($user->save()) {
                    $this->redirect(TreTodayUrl::getUserUrl($user_back->user_id, $user_back->user_name));
                }
            }

        }

        $user->website = $user_back->website;

        #region SEO
        Yii::app()->clientScript->registerLinkTag('canonical', null, TreTodayCommon::getCurrentUrl());
        Yii::app()->clientScript->registerMetaTag('Rao vặt hot, thông tin cá nhân ' . $user->user_name, 'description');
        Yii::app()->clientScript->registerMetaTag(Yii::app()->params['meta_keywords'], 'keywords');
        $this->pageTitle = 'Rao vặt hot | Thông tin tài khoản ' . $user->user_name;
        #endregion SEO

        $this->render('index', array('model' => $user, 'user_id' => $id, 'products' => $products, 'buyWay' => $buyWay, 'guestBooks' => $guestBooks, 'total' => $total));
    }

    public function beforeaction() {
        if (!isset(Yii::app()->request->cookies['rvhlayout'])) {
            $cookie = new  CHttpCookie('layout', '//layouts/main');
            $cookie->expire = time() + 60 * 60 * 24 * 10; //10 days
            Yii::app()->request->cookies['rvhlayout'] = $cookie;
        }
        $cookie = Yii::app()->request->cookies['rvhlayout'];
        $this->layout = $cookie->value;
        return true;
    }

    public function actionLogin() {

        if (!defined('CRYPT_BLOWFISH') || !CRYPT_BLOWFISH)
            throw new CHttpException(500, "This application requires that PHP was compiled with Blowfish support for crypt().");
        if (!Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
        }

        $model = new BackendLoginForm();

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['BackendLoginForm'])) {
            $model->attributes = $_POST['BackendLoginForm'];
            $model->password = md5($model->password);

            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()) {
                $session = Yii::app()->session['up_product'];
                if ($session != null) {
                    $this->redirect(TreTodayUrl::getUpProductUrl());
                }
                $this->redirect(TreTodayUrl::home());
            }

        }
        #region SEO
        Yii::app()->clientScript->registerLinkTag('canonical', null, TreTodayCommon::getCurrentUrl());
        Yii::app()->clientScript->registerMetaTag("Rao vặt hot, đăng nhập vào tài khoản của bạn", 'description');
        Yii::app()->clientScript->registerMetaTag(Yii::app()->params['meta_keywords'], 'keywords');
        $this->pageTitle = 'Rao vặt hot | Đăng nhập';
        #endregion SEO

        $this->render('login', array('model' => $model));
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(TreTodayUrl::home());
    }

    public function actionRegister() {
        $model = new UserBack();
        if (isset($_POST['UserBack'])) {

            $model->attributes = $_POST['UserBack'];
            $model->confirm_password = $_POST['UserBack']['confirm_password'];
            $model->website = $_POST['UserBack']['website'];
            $model->categories = $_POST['UserBack']['categories'];
            $file = CUploadedFile::getInstance($model, 'image');

            $model->validate();
            $pass = $model->password;
            $address = $_POST['UserBack']['address'];
            $phone = $_POST['UserBack']['phone'];
            $ym = $_POST['UserBack']['yahoo'];
            $model->validate();
            if (count($model->getErrors()) == 0) {
                $model->password = md5($model->password);
                $model->confirm_password = md5($model->confirm_password);
                $model->register_date = date("Y-m-d");
                if ($file != null) {

                    $imageVariables = getimagesize($file->tempName);
                    $file = EUploadedImage::getInstance($model, 'image');
                    $arr_size = TreTodayCommon::getResizeImage($imageVariables[0], $imageVariables[1]);
                    $file->maxWidth = $arr_size['width'];
                    $file->maxHeight = $arr_size['height'];
                    $rnd = rand(0, 999999);
                    $fileName = "{$rnd}.jpg";
                    $base = TreTodayCommon::createFolder('avata');
                    $base = $base . '/' . $fileName;
                    if ($file->saveAs($base)) {
                        $model->avata_url = TreTodayCommon::generateImagePath('avata', $fileName);
                        $model->group_code = 'user';

                        $model->activation_code = md5(rand(1, 99999) * time());
                        $model->save();

                    }
                } else {
                    $model->activation_code = md5(rand(1, 99999) * time());
                    $model->group_code = 'user';
                    $model->avata_url = '';
                    $model->save();
                }

                $content = '<table width="90%" cellspacing="2" cellpadding="2" border="0" align="center">';
                $content .= '<tbody>';
                $content .= '<tr>';
                $content .= '<td align="center"><strong>Thông tin kích hoạt tài khoản</strong></td>';
                $content .= '</tr>';
                $content .= '<tr>';
                $content .= '<td>Username : ' . $model->user_name . '</td>';
                $content .= '</tr>';
                $content .= '<tr>';
                $content .= '<td>Email : ' . $model->email . '</td>';
                $content .= '</tr>';
                $content .= '<tr>';
                $content .= ' <td>Click vào <a href="' . TreTodayUrl::getActiveAccount($model->activation_code) . '">đây</a> để kích hoạt</td>';
                $content .= ' </tr>';
                $content .= '<tr>';
                $content .= '<td>Website : <a href="' . TreTodayUrl::home() . '">' . TreTodayUrl::home() . '</a></td>';
                $content .= '</tr>';
                $content .= '</tbody>';
                $content .= '</table>';

                $smtp = Yii::app()->params['mailer'];
                Yii::app()->mailer->Host = $smtp['host'];
                Yii::app()->mailer->IsSMTP();
                Yii::app()->mailer->SMTPAuth = true;
                Yii::app()->mailer->CharSet = 'UTF-8';
                Yii::app()->mailer->From = $smtp['email'];
                Yii::app()->mailer->Port = $smtp['port'];
                Yii::app()->mailer->Username = $smtp['user'];
                Yii::app()->mailer->Password = $smtp['pass'];
                Yii::app()->mailer->FromName = $smtp['name'];
                Mailer::sendEmail($model->email, 'Kích hoạt tài khoản raovathot', $content);

                $raovat = new UserRaoVatInfo();
                $raovat->first_name = $model->first_name;
                $raovat->last_name = $model->last_name;
                $raovat->ym = $ym;
                $raovat->phone = $phone;
                $raovat->address = $address;
                $raovat->avata_url = $model->avata_url;
                $raovat->user_id = $model->user_id;
                $raovat->user_name = $model->user_name;
                $raovat->join_time = time();
                $raovat->level = 0;
                $raovat->user_id = $model->user_id;
                $raovat->save();

                $form = new BackendLoginForm();
                $form->username = $model->email;
                $form->password = $model->password;
                $form->login();
                Yii::app()->user->setFlash('success', "Bạn đã tạo tài khoản thành công. Vui lòng kiểm tra hộp thư để kích hoạt tài khoản.");
                $session = Yii::app()->session['up_product'];
                if ($session != null) {
                    $this->redirect(TreTodayUrl::getUpProductUrl());
                }

                $this->redirect(TreTodayUrl::home());
            }

        }

        #region SEO
        Yii::app()->clientScript->registerLinkTag('canonical', null, TreTodayCommon::getCurrentUrl());
        Yii::app()->clientScript->registerMetaTag("Rao vặt hot, đăng ký tài khoản mới", 'description');
        Yii::app()->clientScript->registerMetaTag(Yii::app()->params['meta_keywords'], 'keywords');
        $this->pageTitle = 'Rao vặt hot | Đăng ký tài khoản';
        #endregion SEO
        $categories = Category::model()->findAll(array(
            'select' => '*',
            'condition' => 'parent_id >0 '
        ));
        $this->render('register', array('model' => $model, 'categories' => $categories));
    }

    public function actionEditBuyWay() {
        if (!isset($_GET['user_id'])) throw new CHttpException(999, 'Invalid request');
        if (Yii::app()->user->id != $_GET['user_id']) throw new CHttpException(999, 'Invalid request');

        $buyWay = BuyWay::model()->findByAttributes(array('user_id' => $_GET['user_id']));
        if ($buyWay == null) {
            $buyWay = new BuyWay();
        }

        #region SEO
        Yii::app()->clientScript->registerLinkTag('canonical', null, TreTodayCommon::getCurrentUrl());
        Yii::app()->clientScript->registerMetaTag("Rao vặt hot, chỉnh sửa phương thức mua hàng", 'description');
        Yii::app()->clientScript->registerMetaTag(Yii::app()->params['meta_keywords'], 'keywords');
        $this->pageTitle = 'Rao vặt hot | Chỉnh sửa phương thức mua hàng';
        #endregion SEO

        $this->render('buyWay', array('model' => $buyWay));
    }

    public function actionActiveAccount() {
        if (!isset($_GET['code'])) throw new CDbException(999, 'Invalid request');
        $user = UserBack::model()->findByAttributes(array('activation_code' => $_GET['code']));

        if ($user == null) $this->redirect(TreTodayUrl::home());
        $user->status = 1;
        $user->activation_code = '';
        $user->save();
        Yii::app()->user->setFlash('success', "Bạn đã kích hoạt tài khoản thành công.");

        #region SEO
        Yii::app()->clientScript->registerLinkTag('canonical', null, TreTodayCommon::getCurrentUrl());
        Yii::app()->clientScript->registerMetaTag("Rao vặt hot, kích hoạt tài khoản của bạn", 'description');
        Yii::app()->clientScript->registerMetaTag(Yii::app()->params['meta_keywords'], 'keywords');
        $this->pageTitle = 'Rao vặt hot | Kích hoạt tài khoản ' . $user->user_name;
        #endregion SEO

        $this->redirect(TreTodayUrl::home());

    }

}